package com.xykj.enterprise.wechat.core.dao.corp;

import com.xykj.enterprise.wechat.core.model.dodb.AuthCorp;
import com.xykj.enterprise.wechat.util.time.TimeUtil;
import org.springframework.stereotype.Repository;

import java.util.Date;

/**
 * @Author zhouxu
 * @create 2021-03-31 14:46
 */
@Repository
public class AuthCorpDaoImpl implements AuthCorpDao {
    @Override
    public String save(
            String corpid,
            String accessToken,
            Integer expiresIn,
            String permanentCode,
            String authCorpInfo,
            String authInfo,
            String authUserInfo,
            String dealerCorpInfo,
            String registerCodeInfo
    ) {
        AuthCorp authCorp = new AuthCorp();
        authCorp.setCorpid(corpid);
        authCorp.setAccessToken(accessToken);
        authCorp.setPermanentCode(permanentCode);
        authCorp.setAuthCorpInfo(authCorpInfo);
        authCorp.setAuthInfo(authInfo);
        authCorp.setAuthUserInfo(authUserInfo);
        authCorp.setDealerCorpInfo(dealerCorpInfo);
        authCorp.setRegisterCodeInfo(registerCodeInfo);
        Date now = new Date();
        authCorp.setCreateTime(now);
        authCorp.setTokenExpTime(TimeUtil.addTime(now, expiresIn));
        authCorp.save();
        return authCorp.getCorpid();
    }

    @Override
    public void update(
            String corpid,
            String accessToken,
            Integer expiresIn,
            String permanentCode,
            String authCorpInfo,
            String authInfo,
            String authUserInfo,
            String dealerCorpInfo,
            String registerCodeInfo
    ) {
        AuthCorp authCorp = AuthCorp.dao.findById(corpid);
        authCorp.setCorpid(corpid);
        authCorp.setAccessToken(accessToken);
        authCorp.setPermanentCode(permanentCode);
        authCorp.setAuthCorpInfo(authCorpInfo);
        authCorp.setAuthInfo(authInfo);
        authCorp.setAuthUserInfo(authUserInfo);
        authCorp.setDealerCorpInfo(dealerCorpInfo);
        authCorp.setRegisterCodeInfo(registerCodeInfo);
        Date now = new Date();
        authCorp.setCreateTime(now);
        authCorp.setTokenExpTime(TimeUtil.addTime(now, expiresIn));
        authCorp.update();
    }

    @Override
    public AuthCorp getByCorpid(String corpid) {
        return AuthCorp.dao.findById(corpid);
    }

    @Override
    public AuthCorp resetAccessToken(String corpid, String accessToken, Integer expireId) {
        AuthCorp authCorp = AuthCorp.dao.findById(corpid);
        if (authCorp != null) {
            authCorp.setAccessToken(accessToken);
            Date now = new Date();
            authCorp.setTokenResetTime(now);
            authCorp.setTokenExpTime(TimeUtil.addTime(now, expireId));
            authCorp.update();
        }
        return authCorp;
    }

}
